package com.example.timeactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private Handler myHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.tvTime);

        // 注册EventBus
        EventBus.getDefault().register(this);

        // 创建Handler实例
        myHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // 当接收到消息时更新UI
                textView.setText(msg.obj.toString());
            }
        };

        // 创建并启动线程
        MyThread myThread = new MyThread();
        myThread.start();
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000); // 延时1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 获取当前时间
                Calendar date = Calendar.getInstance();
                int year = date.get(Calendar.YEAR);
                int month = date.get(Calendar.MONTH) + 1;
                int day = date.get(Calendar.DAY_OF_MONTH);
                int hour = date.get(Calendar.HOUR_OF_DAY);
                int minute = date.get(Calendar.MINUTE);
                int second = date.get(Calendar.SECOND);

                // 格式化时间字符串
                String dateTime = String.format("%04d年%02d月%02d日\n%02d:%02d:%02d",
                        year, month, day, hour, minute, second);

                // 发送事件到EventBus
                EventBus.getDefault().post(new MessageEvent(dateTime));
            }
        }
    }

    // EventBus解注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    // 接收消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleMessage(MessageEvent msgEvent) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText(msgEvent.getdateTime());
            }
        });
    }

}
